package com.woniu.service.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
@Slf4j
public class OkHttpUtils {
    /**
     * 将MultipartFile类型的文件上传到Linux服务器
     *
     * @param file     MultipartFile类型的文件
     * @param url      Linux服务器的URL
     * @param fileName 上传到Linux服务器上的文件名
     * @throws IOException
     */
    public static void uploadFile(MultipartFile file, String url, String fileName) throws IOException {
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", fileName, RequestBody.create(MediaType.parse("application/octet-stream"), file.getBytes()))
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            log.error("上传失败原因: " + response);
            throw new IOException("上传失败原因: " + response);
        }
    }
}